#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/5/9 10:45
# @Author  : Chenmm
# @File    : Events.py
# @Software: PyCharm
# @Des: fastapi事件监听


from typing import Callable
from fastapi import FastAPI
from database.mysql import register_mysql, close_mysql
from database.redis import sys_cache, code_cache


def startup(app: FastAPI) -> Callable:
    """
    FastApi 启动完成事件
    :param app: FastAPI
    :return: start_app
    """
    async def app_start() -> None:
        # APP启动完成后触发
        print("启动完毕")
        # 注册数据库
        await register_mysql(app)
        # 注入缓存到app.state
        app.state.cache = await sys_cache()
        app.state.code_cache = await code_cache()
        print("注册缓存完成")

        pass
    return app_start


def stopping(app: FastAPI) -> Callable:
    """
    FastApi 停止事件
    :param app: FastAPI
    :return: stop_app
    """
    async def stop_app() -> None:
        # APP停止时触发
        print("停止")
        await close_mysql(app)
        # 关闭redis
        await app.state.cache.close()
        await app.state.cache.wait_closed()

        await app.state.code_cache.close()
        await app.state.code_cache.wait_closed()
        print("redis closed")
        pass

    return stop_app